require('../css/login.less');


document.ready(function () {
    // 非空验证
    let user = document.querySelector('.user');
    let pwd = document.querySelector('.pwd');
    let btn = document.querySelector('.btn');
    let inp = document.querySelectorAll('input');
    let error = document.querySelector('.errors');
    inp.forEach(function (e, i) {
        e.addEventListener('blur', function () {
            let bool = window.common.errors(e.value);
            if (bool == false) {
                if (i === 0) {
                    error.textContent = "输入账号为空"
                    return;
                }
                if (i === 1) {
                    error.textContent = "输入密码为空"
                    return;
                }
            } else if (bool == true) {
                error.textContent = "";
            }
        })
    })
    btn.addEventListener('click', function () {
        // 请求登录接口
        $http.post('/users/login', {
            account: user.value,
            password: pwd.value
        }, function (res) {
            if (res.status === 0) { // 请求成功
                window.confirm('登录成功');
                //把数据存到本地存储
                let obj = {
                    user:res.data.user
                };
                let toObj = JSON.stringify(obj);
                localStorage.setItem('user', toObj);
                // Toast显示
                window.utils.showToast(0, '登录成功!');
                //跳转首页
                window.location.href = 'http://localhost:666/index.html';
            }
            else {
                window.setTimeout(function () {
                    window.utils.showToast(1, '登录失败!');
                }, 1500)
                window.confirm(res.msg);
            }
        })
    })
})